#!/bin/sh
# Copyright (C) 2011 O.S. Systems Software LTDA.
# Licensed on MIT

finish_enabled() {
    # shellcheck disable=SC2154
    if [ "$bootparam_recovery" = "true" ]; then
        if [ -n "${ADBD_PID}" ]; then
            # adbd is not a child process so cannot wait
            while kill -0  "${ADBD_PID}" 2>/dev/null; do sleep 1; done
        fi
    fi
    return 0
}

relocate_log_mount() {
    # Preserve log file in rootfs
    # Move the /run mountpoint to the rootfs mountpoint
    if [ -d "${ROOTFS_DIR}/run" ]; then
        if mountpoint '/run' > /dev/null; then
            mount -n -o move /run "${ROOTFS_DIR}/run"
        fi
    else
        # Older releases do not create /run so use /tmp instead
        if mountpoint '/run' > /dev/null; then
            mount -n -o move /run "${ROOTFS_DIR}/tmp"
        fi
    fi
    sync "${ROOTFS_DIR}/run" "${ROOTFS_DIR}/tmp" || true
}

finish_run() {
    if [ -n "$ROOTFS_DIR" ]; then
        if [ ! -d $ROOTFS_DIR/dev ]; then
            fatal "ERROR: There's no '/dev' on rootfs."
        fi

        info "Switching root to '$ROOTFS_DIR'..."

        debug "Moving /dev, /proc and /sys onto rootfs..."
        mount --move /dev $ROOTFS_DIR/dev
        mount --move /proc $ROOTFS_DIR/proc
        mount --move /sys $ROOTFS_DIR/sys
        debug "Moving log mount into rootfs..."
        relocate_log_mount

        cd $ROOTFS_DIR
        exec switch_root $ROOTFS_DIR ${bootparam_init:-/sbin/init}
    else
        debug "No rootfs has been set"
    fi
}
